<script setup lang="ts">
import * as Icons from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const routes = router.options.routes[0].children

defineEmits(['open', 'close'])

// 动态获取图标组件
const getIcon = (iconName: string) => {
  return Icons[iconName as keyof typeof Icons]
}

const handleMenuClick = (route: string) => {
  // 处理空路径情况
  if (!route.endsWith('/')) {
    router.push(route)
  } else {
    // 如果是空路径，使用 alias 中的第一个路径
    const path = route.slice(0, -1) + '/staff'
    router.push(path)
  }
}
</script>

<template>
  <template v-for="route in routes" :key="route.path">
    <!-- 有子菜单的情况 -->
    <el-sub-menu v-if="route.meta && route.children" :index="route.path">
      <template #title>
        <el-icon><component :is="getIcon(route.meta.icon)" /></el-icon>
        <span>{{ route.meta.name }}</span>
      </template>
      <!-- 递归渲染子菜单 -->
      <template v-for="child in route.children" :key="child.path">
        <el-menu-item 
          :index="route.path + '/' + child.path"
          @click="handleMenuClick(route.path + '/' + child.path)"
        >
          <el-icon><component :is="getIcon(child.meta.icon)" /></el-icon>
          <span>{{ child.meta.name }}</span>
        </el-menu-item>
      </template>
    </el-sub-menu>
    <!-- 没有子菜单的情况 -->
    <el-menu-item 
      v-else-if="route.meta" 
      :index="route.path"
      @click="handleMenuClick(route.path)"
    >
      <el-icon><component :is="getIcon(route.meta.icon)" /></el-icon>
      <span>{{ route.meta.name }}</span>
    </el-menu-item>
  </template>
</template>

<style scoped>
.el-icon {
  margin-right: 8px;
}
</style>
